package de.sp.games.snake12k;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class SaveSystem
{
	private static SaveSystem INSTANCE = new SaveSystem();
	
	private File file = new File("saves/snake12k.dat");
	DataOutputStream dataOutputStream;
	DataInputStream dataInputStream;
	
	private SaveSystem() { }

	public boolean existFile()
	{
		return file.exists();
	}
	
	/* Loading */
	public Score loadScore()
	{
		int index = 0;
		String name = "ERROR";
		int scoreNumber = 0;
		try
		{
			name = dataInputStream.readUTF();
			scoreNumber = dataInputStream.readInt();
			index = dataInputStream.readInt();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return new Score(name, scoreNumber, index);
	}
	
	public void startInputStream()
	{
		try
		{
			dataInputStream = new DataInputStream(new FileInputStream(file));
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	
	/* Saving */
	public void writeScore(final Score score)
	{
		try
		{
			dataOutputStream.writeUTF(score.getName());
			dataOutputStream.writeInt(score.getScoreNumber());
			dataOutputStream.writeInt(score.getIndex());
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	public void startOutputStream()
	{
		try
		{
			dataOutputStream = new DataOutputStream(new FileOutputStream(file));
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	
	public void closeOutputStream()
	{
		try
		{
			dataOutputStream.close();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	/* Saving - END */
	
	public static SaveSystem getInstance() { return INSTANCE; }
}
